﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Lrd.Template.Core.Infrastructure.Reflection;


namespace Lrd.Template.Core.Infrastructure.Extensions
{
    public static partial class Extensions
    {


        /// <summary>
        /// 得到或者添加TypeFinder
        /// </summary>
        /// <typeparam name="TTypeFinder"></typeparam>
        /// <typeparam name="TImplementation"></typeparam>
        /// <param name="services"></param>
        /// <returns></returns>
        public static TTypeFinder GetOrAddTypeFinder<TTypeFinder, TImplementation>(this IServiceCollection services) where TTypeFinder : class
            where TImplementation : class, TTypeFinder
        {

            var allAssemblyFinder = services.GetService<IAllAssemblyFinder>();
            if (allAssemblyFinder is null)
            {
                throw new Exception($"该{nameof(IAllAssemblyFinder)}接口实例，没有注入!!!");
            }
            var typeFinder = services.GetOrAddSingletonService<TTypeFinder, TImplementation>();
            return typeFinder;
        }



        /// <summary>
        /// 得到注入服务
        /// </summary>
        /// <typeparam name="TType"></typeparam>
        /// <param name="services"></param>
        /// <returns></returns>
        public static TType GetService<TType>(this IServiceCollection services)
        {
            var provider = services.BuildServiceProvider();
            return  provider.GetService<TType>();
        }

        /// <summary>
        /// 得到或添加Singleton服务
        /// </summary>
        /// <typeparam name="TType"></typeparam>
        /// <typeparam name="TImplementation"></typeparam>
        /// <param name="services"></param>
        /// <returns></returns>

        public static TType GetOrAddSingletonService<TType, TImplementation>(this IServiceCollection services) where TType : class
            where TImplementation : class, TType
        {
            var type= services.GetService<TType>();
            if (type  is null)
            {
                services.AddSingleton<TType, TImplementation>();
                type = services.GetService<TType>(); 
            }

            return type;
        }
    }
}
